//
//  SLEditViewController.m
//  DarkMode
//
//  Created by wsl on 2019/10/12.
//  Copyright © 2019 wsl. All rights reserved.
//

#import "SLEditVideoController.h"
#import <Photos/Photos.h>
#import "UIView+SLImage.h"
#import "SLBlurView.h"
#import "SLEditMenuView.h"
#import "SLAvPlayer.h"
#import "SLAvCaptureTool.h"
#import "SLAvEditExport.h"
#import "SLEditSelectedBox.h"
#import "SLImage.h"
#import "SLImageView.h"
#import "SLDrawView.h"
#import "SLEditTextView.h"
#import "SLEditVideoClipping.h"
#import "UIImage+SLCommon.h"

@interface SLEditVideoController () <UIGestureRecognizerDelegate, SLAvPlayerDelegate>

@property (nonatomic, strong) UIImageView *preview; // 预览视图 展示编辑的图片或视频
@property (nonatomic, strong) SLAvPlayer *avPlayer;  //视频播放预览

@property (nonatomic, strong) UIButton *saveAlbumBtn;  //保存到相册
@property (nonatomic,strong) UIButton *cancelBtn;

@end

@implementation SLEditVideoController

#pragma mark - Override
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    _avPlayer.delegate = nil;
    [_avPlayer stop];
    _avPlayer = nil;
}
- (BOOL)prefersStatusBarHidden {
    return YES;
}
- (void)dealloc {
    NSLog(@"视频编辑视图释放了");
}
#pragma mark - UI
- (void)setupUI {
    self.view.backgroundColor = [UIColor blackColor];
    [self.view addSubview:self.preview];
    
    self.avPlayer.url = self.videoPath;
    self.avPlayer.delegate = self;
    if (self.avPlayer.naturalSize.width != CGSizeZero.width) {
         self.preview.sl_height = self.preview.sl_width *  self.avPlayer.naturalSize.height/ self.avPlayer.naturalSize.width;
    }
    self.avPlayer.monitor = self.preview;
    self.preview.center = CGPointMake(self.view.sl_width/2.0, self.view.sl_height/2.0);
    [self.avPlayer play];

    [self.view addSubview:self.saveAlbumBtn];
  
    [self.view addSubview:self.cancelBtn];
    
}
//置顶视图
- (void)topSelectedView:(UIView *)topView {
    [self.preview bringSubviewToFront:topView];
  
    [SLDelayPerform sl_cancelDelayPerform]; //取消延迟执行
   
}

// Gif CALayer关键帧动画
- (CAKeyframeAnimation *)animationForGifWithImage:(SLImage *)image {
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"contents"];
    NSMutableArray * frames = [NSMutableArray new];
    NSMutableArray *times = [NSMutableArray arrayWithCapacity:3];
    CGFloat currentTime = 0;
    CGFloat totalTime = image.totalTime;
    NSInteger frameCount = image.frameCount;
    for (int i = 0; i < frameCount; ++i) {
        [times addObject:[NSNumber numberWithFloat:(currentTime / totalTime)]];
        currentTime += [image imageDurationAtIndex:i];
        [frames addObject:(__bridge id)[image imageAtIndex:i].CGImage];
    }
    animation.keyTimes = times;
    animation.values = frames;
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
    animation.duration = totalTime;
    animation.repeatCount = HUGE_VALF;
    return animation;
}

#pragma mark - Getter
- (UIImageView *)preview {
    if (_preview == nil) {
        _preview = [[UIImageView alloc] initWithFrame:self.view.bounds];
        _preview.contentMode = UIViewContentModeScaleAspectFill;
        _preview.backgroundColor = [UIColor blackColor];
        _preview.userInteractionEnabled = YES;
        _preview.clipsToBounds = YES;
    }
    return _preview;
}
- (SLAvPlayer *)avPlayer {
    if (!_avPlayer) {
        _avPlayer = [[SLAvPlayer alloc] init];
    }
    return _avPlayer;
}
- (UIButton *)cancelBtn{
    if (!_cancelBtn) {
        _cancelBtn = [[UIButton alloc]initWithFrame:CGRectMake(16, 56, 30, 30)];
        [_cancelBtn setImage:[UIImage imageNamed:@"zl_retake"] forState:UIControlStateNormal];
        [_cancelBtn addTarget:self action:@selector(againShotBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _cancelBtn;
}

- (UIButton *)saveAlbumBtn {
    if (_saveAlbumBtn == nil) {
        _saveAlbumBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 70, 30)];
        _saveAlbumBtn.cl_bottom = self.view.sl_height - 80;
        _saveAlbumBtn.cl_right = kScreenW - 16;
//        [_saveAlbumBtn setImage:[UIImage imageNamed:@"social_confirm_tag"] forState:UIControlStateNormal];
        [_saveAlbumBtn setBackgroundImage:[UIImage imageNamed:@"social_confirm_tag"] forState:UIControlStateNormal];
        
        [_saveAlbumBtn addTarget:self action:@selector(saveAlbumBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
        
        [_saveAlbumBtn setTitle:@"完成" forState:UIControlStateNormal];
        [_saveAlbumBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _saveAlbumBtn.titleLabel.font = font(16);
    }
    return _saveAlbumBtn;
}

#pragma mark - Events Handle
//再试一次 继续拍摄
- (void)againShotBtnClicked:(id)sender {
    [self dismissViewControllerAnimated:NO completion:nil];
}
//保存到相册
- (void)saveAlbumBtnClicked:(id)sender {
    
    if (self.videoPath.path.length != 0) {
        [self dismissViewControllerAnimated:NO completion:nil];
        UIViewController *parentVC = self.presentingViewController;
        UIViewController *bottomVC;
        while (parentVC) {
            bottomVC = parentVC;
            parentVC = parentVC.presentingViewController;
        }
        [bottomVC dismissViewControllerAnimated:NO completion:nil];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"updateReleaseVideo" object:nil userInfo:@{@"data":self.videoPath.path,@"stauts":@(self.isOpusList)}];
    }
//    //视频录入完成之后在将视频保存到相簿  如果视频过大的话，建议创建一个后台任务去保存到相册
//    PHPhotoLibrary *photoLibrary = [PHPhotoLibrary sharedPhotoLibrary];
//    [photoLibrary performChanges:^{
//        [PHAssetChangeRequest creationRequestForAssetFromVideoAtFileURL:self.videoPath];
//    } completionHandler:^(BOOL success, NSError * _Nullable error) {
//
//        SL_DISPATCH_ON_MAIN_THREAD(^{

//        });
//        if (success) {
//            [[NSNotificationCenter defaultCenter] postNotificationName:@"updateReleaseSocialList" object:nil];
//        }
//    }];
}


// 视频保存回调

- (void)video:(NSString *)videoPath didFinishSavingWithError:(NSError *)error contextInfo: (void *)contextInfo {
    SL_DISPATCH_ON_MAIN_THREAD(^{
        [self dismissViewControllerAnimated:NO completion:nil];
        UIViewController *parentVC = self.presentingViewController;
        UIViewController *bottomVC;
        while (parentVC) {
            bottomVC = parentVC;
            parentVC = parentVC.presentingViewController;
        }
        [bottomVC dismissViewControllerAnimated:NO completion:nil];
    });
    if (error) {
        NSLog(@"保存图片出错%@", error.localizedDescription);
    } else {
        NSLog(@"保存图片成功");
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"updateReleaseVideo" object:nil userInfo:@{@"data":videoPath}];
        
    }
}

- (void)setAuthStatusWithMessage:(NSString *)message{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"" message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [alertController dismissViewControllerAnimated:YES completion:nil];
        // 去设置相册权限
        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        if ([[UIApplication sharedApplication]canOpenURL:url]) {
            [[UIApplication sharedApplication]openURL:url options:@{} completionHandler:nil];
        }
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [alertController dismissViewControllerAnimated:YES completion:nil];
    }];
    [confirmAction setValue:[RPAppManager themColor] forKey:@"titleTextColor"];
    [cancelAction setValue:[RPAppManager themColor] forKey:@"titleTextColor"];
    //往alertViewController上添加alertAction
    [alertController addAction:cancelAction];
    [alertController addAction:confirmAction];
    [self presentViewController:alertController animated:YES completion:nil];
    
}


//保存图片完成后调用的方法
- (void)savedPhotoImage:(UIImage*)image didFinishSavingWithError:(NSError *)error contextInfo: (void *)contextInfo {
    SL_DISPATCH_ON_MAIN_THREAD(^{
        [self dismissViewControllerAnimated:NO completion:^{
            NSString *result = error ? @"图片保存至相册 失败" : @"图片保存到相册 成功";
            NSLog(@"%@", result);
        }];
    });
}





#pragma mark - UIGestureRecognizerDelegate
// 该方法返回的BOOL值决定了view是否能够同时响应多个手势
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    //     NSLog(@"%@ - %@", gestureRecognizer.class, otherGestureRecognizer.class);
    return YES;
}


@end
